package com.youlu.campus.service.data;

import com.mongodb.client.result.UpdateResult;
import com.youlu.campus.entity.*;
import com.youlu.campus.entity.VO.req.ImportCertificateUpdateVO;
import com.youlu.campus.service.cache.CacheCaCertificateService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CertificateDataService {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private CacheCaCertificateService cacheCaCertificateService;


    public void certificateNoUpdate(String activityId, List<ImportCertificateUpdateVO> list) {
        log.info("获取活动 {} 导入数据:{}", activityId, list.size());
        Integer limit = 100;
        Integer skip = 0;
        List<ImportCertificateUpdateVO> batchDataList = null;
        Integer maxCount = 0;
        do {
            maxCount = skip * limit;
            batchDataList = list.stream().skip(maxCount).limit(limit).collect(Collectors.toList());
            List<String> orderNoList =
                    batchDataList.stream().map(user -> user.getOrderNo()).collect(Collectors.toList());
            Query query = new Query();
            query.addCriteria(Criteria.where("orderNo").in(orderNoList));
            query.addCriteria(Criteria.where("activityId").is(activityId));
            List<OrderInfo> listOrder = this.mongoTemplate.find(query, OrderInfo.class);
            List<ImportCertificateUpdateVO> finalBatchDataList1 = batchDataList;
            listOrder.stream().forEach(orderInfo -> {
                String orderNo = orderInfo.getOrderNo();
                Query query2 = new Query();
                query2.addCriteria(Criteria.where("orderNo").is(orderNo));
                query2.addCriteria(Criteria.where("caGift").is(Boolean.TRUE));
                OOrderInfo subOrder = this.mongoTemplate.findOne(query2, OOrderInfo.class);
                if(Objects.isNull(subOrder)){
                    log.error("订单不存在->{}",orderNo);
                    return;
                }
                String itemInfoId = subOrder.getItemInfoId();
                CaInfo caInfo = this.mongoTemplate.findById(itemInfoId, CaInfo.class);
                CaCertificateLog caCertificateLog = cacheCaCertificateService.getCaCertificate(activityId,
                        orderInfo.getAccountInfoId(), orderInfo.getTaskBizType(), caInfo.getLevel());
                if (Objects.isNull(caCertificateLog)) {
                    return;
                }
                String certificateNoOrigin = caCertificateLog.getCertificateNo();
                Optional<ImportCertificateUpdateVO> orderNoOptional =
                        finalBatchDataList1.stream().filter(user -> user.getOrderNo().equals(orderNo)).findFirst();
                if (!orderNoOptional.isPresent()) {
                    return;
                }
                ImportCertificateUpdateVO importCertificateNo = orderNoOptional.get();
                Query query1 = new Query();
                query1.addCriteria(Criteria.where("id").is(caCertificateLog.getId()));
                Update update = new Update();
                update.set("certificateNo", importCertificateNo.getCertificateNo());
                update.set("mark", "原有-" + certificateNoOrigin);
                update.set("updatedTime", new Date());
                UpdateResult updateResult = this.mongoTemplate.updateFirst(query1, update,
                        CaCertificateLog.class);
                if (updateResult.getModifiedCount() > 0) {
                    query1 = new Query();
                    query1.addCriteria(Criteria.where("certificateNo").is(certificateNoOrigin));
                    query1.addCriteria(Criteria.where("userName").is(importCertificateNo.getName()));
                    UpdateResult updateResult1 = this.mongoTemplate.updateMulti(query1, update,
                            UserCaRecord.class);
                    if (updateResult1.getModifiedCount() == 0) {
                        log.error("更新真伪数据原有编号->{} 现有编号 ->{}", certificateNoOrigin,
                                importCertificateNo.getCertificateNo());
                    }
                } else {
                    log.error("更新编号document原有编号->{} 现有编号 ->{}", certificateNoOrigin,
                            importCertificateNo.getCertificateNo());
                }
            });

            log.info("活动 {} 当前页数-> {} ", activityId, skip + 1);
            skip++;

        } while (maxCount < list.size());
        batchDataList.clear();
        list.clear();
    }


}
